'use client'

import { useEffect, useState } from 'react'
import Link from 'next/link'
import api from '@/lib/api'
import { useAuthStore } from '@/lib/store'
import RequireAuth from '@/components/auth/RequireAuth'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { useForm } from 'react-hook-form'
import { toast } from 'react-hot-toast'
import { Input } from '@/components/ui/input'
import { Button } from '@/components/ui/button'
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form'
import { format } from 'date-fns'

interface Favorite {
  id: number
  created_at: string
  spot: {
    id: number
    name: string
    description: string
    price: number
    images: string
    type: string
  }
}

interface OrderSummary {
  total_orders: number
  total_spent: number
  recent_spots: string[]
}

interface PasswordForm {
  oldPassword: string
  newPassword: string
  confirmPassword: string
}

interface ProfileForm {
  username: string
  email: string
  name: string
  phone: string
  address: string
}

interface Order {
  id: number
  spot_id: number
  quantity: number
  total_price: number
  status: string
  rating?: number
  comment?: string
  commented_at?: string
  is_anonymous?: boolean
  spot: {
    name: string
    images: string
  }
}

export default function ProfilePage() {
  const { user } = useAuthStore()
  const [favorites, setFavorites] = useState<Favorite[]>([])
  const [orders, setOrders] = useState<Order[]>([])
  const [orderSummary, setOrderSummary] = useState<OrderSummary | null>(null)
  const [loading, setLoading] = useState(true)

  const passwordForm = useForm<PasswordForm>()
  const [isSubmitting, setIsSubmitting] = useState(false)

  const profileForm = useForm<ProfileForm>({
    defaultValues: {
      username: user?.username || '',
      email: user?.email || '',
      name: user?.name || '',
      phone: user?.phone || '',
      address: user?.address || ''
    }
  })
  const [isProfileSubmitting, setIsProfileSubmitting] = useState(false)

  const handleDeleteReview = async (orderId: number) => {
    try {
      await api.delete(`/api/orders/${orderId}/review`)
      toast.success('评价已删除')
      fetchData()
    } catch (error: any) {
      toast.error(error.response?.data?.detail || '删除评价失败')
    }
  }

  const fetchData = async () => {
    try {
      setLoading(true)
      const [favoritesRes, summaryRes, ordersRes] = await Promise.all([
        api.get('/api/favorites'),
        api.get('/api/users/order-summary'),
        api.get('/api/orders')
      ])
      setFavorites(favoritesRes.data)
      setOrderSummary(summaryRes.data)
      setOrders(ordersRes.data)
    } catch (error) {
      console.error('Failed to fetch profile data:', error)
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    fetchData()
  }, [])

  const onSubmit = async (data: PasswordForm) => {
    if (data.newPassword !== data.confirmPassword) {
      toast.error('两次输入的新密码不一致')
      return
    }

    try {
      setIsSubmitting(true)
      await api.post('/api/users/change-password', {
        old_password: data.oldPassword,
        new_password: data.newPassword,
      })
      toast.success('密码修改成功')
      passwordForm.reset()
    } catch (error) {
      toast.error('密码修改失败，请检查原密码是否正确')
    } finally {
      setIsSubmitting(false)
    }
  }

  const onProfileSubmit = async (data: ProfileForm) => {
    try {
      setIsProfileSubmitting(true)
      await api.put('/api/users/profile', data)
      toast.success('资料修改成功')
      useAuthStore.getState().updateProfile(data)
    } catch (error) {
      toast.error('资料修改失败')
    } finally {
      setIsProfileSubmitting(false)
    }
  }

  if (loading) {
    return <div>加载中...</div>
  }

  return (
    <RequireAuth>
      <div className="bg-white">
        <div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8 py-8">
          <h1 className="text-2xl font-semibold text-gray-900 mb-6">个人中心</h1>
          
          <Tabs defaultValue="profile" orientation="vertical" className="flex space-x-8">
            <TabsList className="flex flex-col h-fit space-y-2 bg-transparent">
              <TabsTrigger 
                value="profile" 
                className="w-40 justify-start text-left px-4 data-[state=active]:bg-primary data-[state=active]:text-primary-foreground"
              >
                基本信息
              </TabsTrigger>
              <TabsTrigger 
                value="favorites" 
                className="w-40 justify-start text-left px-4 data-[state=active]:bg-primary data-[state=active]:text-primary-foreground"
              >
                我的收藏
              </TabsTrigger>
              <TabsTrigger 
                value="orders" 
                className="w-40 justify-start text-left px-4 data-[state=active]:bg-primary data-[state=active]:text-primary-foreground"
              >
                订单统计
              </TabsTrigger>
              <TabsTrigger 
                value="security" 
                className="w-40 justify-start text-left px-4 data-[state=active]:bg-primary data-[state=active]:text-primary-foreground"
              >
                修改密码
              </TabsTrigger>
              <TabsTrigger 
                value="reviews" 
                className="w-40 justify-start text-left px-4 data-[state=active]:bg-primary data-[state=active]:text-primary-foreground"
              >
                我的评价
              </TabsTrigger>
            </TabsList>

            <div className="flex-1">
              <TabsContent value="profile">
                <Card>
                  <CardHeader>
                    <CardTitle>基本信息</CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div className="space-y-4">
                      <div>
                        <label className="text-sm font-medium text-gray-500">用户名</label>
                        <p className="mt-1 text-base">{user?.username}</p>
                      </div>
                      <div>
                        <label className="text-sm font-medium text-gray-500">邮箱</label>
                        <p className="mt-1 text-base">{user?.email}</p>
                      </div>
                    </div>
                  </CardContent>
                </Card>

                <Card className="mt-6">
                  <CardHeader>
                    <CardTitle>修改资料</CardTitle>
                  </CardHeader>
                  <CardContent>
                    <Form {...profileForm}>
                      <form onSubmit={profileForm.handleSubmit(onProfileSubmit)} className="space-y-4">
                        <FormField
                          control={profileForm.control}
                          name="username"
                          rules={{
                            required: '请输入用户名',
                            minLength: { value: 3, message: '用户名至少3个字符' },
                            pattern: {
                              value: /^[a-zA-Z0-9_-]+$/,
                              message: '用户名只能包含字母、数字、下划线和连字符'
                            }
                          }}
                          render={({ field }) => (
                            <FormItem>
                              <FormLabel>用户名</FormLabel>
                              <FormControl>
                                <Input {...field} placeholder="请输入用户名" />
                              </FormControl>
                              <FormMessage />
                            </FormItem>
                          )}
                        />

                        <FormField
                          control={profileForm.control}
                          name="email"
                          rules={{
                            required: '请输入邮箱',
                            pattern: {
                              value: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i,
                              message: '请输入有效的邮箱地址'
                            }
                          }}
                          render={({ field }) => (
                            <FormItem>
                              <FormLabel>邮箱</FormLabel>
                              <FormControl>
                                <Input {...field} placeholder="请输入邮箱" />
                              </FormControl>
                              <FormMessage />
                            </FormItem>
                          )}
                        />

                        <FormField
                          control={profileForm.control}
                          name="name"
                          render={({ field }) => (
                            <FormItem>
                              <FormLabel>姓名</FormLabel>
                              <FormControl>
                                <Input {...field} placeholder="请输入姓名" />
                              </FormControl>
                              <FormMessage />
                            </FormItem>
                          )}
                        />

                        <FormField
                          control={profileForm.control}
                          name="phone"
                          rules={{
                            pattern: {
                              value: /^1[3-9]\d{9}$/,
                              message: '请输入正确的手机号'
                            }
                          }}
                          render={({ field }) => (
                            <FormItem>
                              <FormLabel>手机号</FormLabel>
                              <FormControl>
                                <Input {...field} placeholder="请输入手机号" />
                              </FormControl>
                              <FormMessage />
                            </FormItem>
                          )}
                        />

                        <FormField
                          control={profileForm.control}
                          name="address"
                          render={({ field }) => (
                            <FormItem>
                              <FormLabel>地址</FormLabel>
                              <FormControl>
                                <Input {...field} placeholder="请输入地址" />
                              </FormControl>
                              <FormMessage />
                            </FormItem>
                          )}
                        />

                        <Button type="submit" disabled={isProfileSubmitting}>
                          {isProfileSubmitting ? '提交中...' : '保存修改'}
                        </Button>
                      </form>
                    </Form>
                  </CardContent>
                </Card>
              </TabsContent>

              <TabsContent value="orders">
                <div className="grid gap-4">
                  <Card>
                    <CardHeader>
                      <CardTitle>订单统计</CardTitle>
                    </CardHeader>
                    <CardContent>
                      <div className="space-y-2">
                        <div className="flex justify-between">
                          <span>总订单数</span>
                          <span>{orderSummary?.total_orders || 0}</span>
                        </div>
                        <div className="flex justify-between">
                          <span>总消费</span>
                          <span className="text-red-500">¥{orderSummary?.total_spent || 0}</span>
                        </div>
                      </div>
                    </CardContent>
                  </Card>

                  <Card>
                    <CardHeader>
                      <CardTitle>最近游玩</CardTitle>
                    </CardHeader>
                    <CardContent>
                      <ul className="space-y-2">
                        {orderSummary?.recent_spots.map((spot, index) => (
                          <li key={index} className="flex items-center">
                            <span className="text-sm">{spot}</span>
                          </li>
                        ))}
                      </ul>
                    </CardContent>
                  </Card>
                </div>
              </TabsContent>

              <TabsContent value="favorites">
                <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6">
                  {favorites.map(({ spot }) => (
                    <Link href={`/spots/${spot.id}`} key={spot.id}>
                      <div className="border rounded-lg overflow-hidden hover:shadow-lg transition-shadow">
                        {spot.images && (
                          <img
                            src={spot.images.split(',')[0]}
                            alt={spot.name}
                            className="w-full h-48 object-cover"
                          />
                        )}
                        <div className="p-4">
                          <h3 className="font-semibold">{spot.name}</h3>
                          <p className="text-sm text-gray-500 mt-1">{spot.type}</p>
                          <p className="text-red-500 mt-2">¥{spot.price}</p>
                        </div>
                      </div>
                    </Link>
                  ))}
                </div>
              </TabsContent>

              <TabsContent value="security">
                <Card>
                  <CardHeader>
                    <CardTitle>修改密码</CardTitle>
                  </CardHeader>
                  <CardContent>
                    <Form {...passwordForm}>
                      <form onSubmit={passwordForm.handleSubmit(onSubmit)} className="space-y-4">
                        <FormField
                          control={passwordForm.control}
                          name="oldPassword"
                          rules={{ required: '请输入原密码' }}
                          render={({ field }) => (
                            <FormItem>
                              <FormLabel>原密码</FormLabel>
                              <FormControl>
                                <Input type="password" {...field} />
                              </FormControl>
                              <FormMessage />
                            </FormItem>
                          )}
                        />

                        <FormField
                          control={passwordForm.control}
                          name="newPassword"
                          rules={{ 
                            required: '请输入新密码',
                            minLength: { value: 6, message: '密码至少6个字符' }
                          }}
                          render={({ field }) => (
                            <FormItem>
                              <FormLabel>新密码</FormLabel>
                              <FormControl>
                                <Input type="password" {...field} />
                              </FormControl>
                              <FormMessage />
                            </FormItem>
                          )}
                        />

                        <FormField
                          control={passwordForm.control}
                          name="confirmPassword"
                          rules={{ required: '请确认新密码' }}
                          render={({ field }) => (
                            <FormItem>
                              <FormLabel>确认新密码</FormLabel>
                              <FormControl>
                                <Input type="password" {...field} />
                              </FormControl>
                              <FormMessage />
                            </FormItem>
                          )}
                        />

                        <Button type="submit" disabled={isSubmitting}>
                          {isSubmitting ? '提交中...' : '修改密码'}
                        </Button>
                      </form>
                    </Form>
                  </CardContent>
                </Card>
              </TabsContent>

              <TabsContent value="reviews">
                <Card>
                  <CardHeader>
                    <CardTitle>我的评价</CardTitle>
                  </CardHeader>
                  <CardContent>
                    {orders
                      .filter(order => order.rating)
                      .map(order => (
                        <div key={order.id} className="border-b py-4 last:border-0">
                          <div className="flex justify-between items-start">
                            <div>
                              <h3 className="font-medium">{order.spot.name}</h3>
                              <div className="flex items-center mt-1">
                                {[1, 2, 3, 4, 5].map((value) => (
                                  <svg
                                    key={value}
                                    className={`h-4 w-4 ${
                                      value <= (order.rating || 0) ? 'text-yellow-400' : 'text-gray-200'
                                    }`}
                                    fill="currentColor"
                                    viewBox="0 0 20 20"
                                  >
                                    <path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z" />
                                  </svg>
                                ))}
                              </div>
                              <p className="mt-2 text-gray-600">{order.comment}</p>
                              <p className="mt-1 text-sm text-gray-500">
                                {format(new Date(order.commented_at || ''), 'yyyy年MM月dd日')}
                              </p>
                            </div>
                            <Button
                              variant="outline"
                              size="sm"
                              onClick={() => handleDeleteReview(order.id)}
                            >
                              删除评价
                            </Button>
                          </div>
                        </div>
                      ))}

                    {orders.filter(order => order.rating).length === 0 && (
                      <div className="text-center text-gray-500 py-8">
                        暂无评价记录
                      </div>
                    )}
                  </CardContent>
                </Card>
              </TabsContent>
            </div>
          </Tabs>
        </div>
      </div>
    </RequireAuth>
  )
} 